<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodItem :good="good" />
      </li>
    </ul>
  </div>
  <!-- 上拉加载更多 -->
  <XtxInfiniteLoad
    :isLoading="isLoading"
    :isFinished="isFinished"
    @load="getNextPage"
  />
</template>

<script>
import GoodItem from './good-item.vue'
import { findSubCategoryGoods } from '@/api/category.js'
import { ref, inject, watch } from 'vue'
import { useRoute } from 'vue-router'
// 抽离列表渲染数据和逻辑
function useList (filterParams) {
  const goodList = ref([])
  // 请求参数
  const route = useRoute()
  const requestParams = {
    page: 0,
    pageSize: 20,
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  }

  // 实现上拉加载更多
  const isLoading = ref(false)
  const isFinished = ref(false)

  // 下拉加载更多回调函数
  const getNextPage = async () => {
    /**
       * 1.开启列表加载，显示loading => isLoading = true
       * 2.发请求获取列表数据
       * 3.获取到数据后追加到列表
       * 4.关闭加载状态
       * 5.判断列表数据是否加载完成 => 根据list长度和后台total对比 => 加载完将isFinished = true
       */
    isLoading.value = true

    requestParams.page++
    const { result: res } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    console.log('商品', res)
    goodList.value.push(...res.items)
    isLoading.value = false
    if (goodList.value.length === res.counts) {
      isFinished.value = true
    }
  }
  // onMounted(() => {
  //   getGoodsList()
  // })
  return { goodList, requestParams, isFinished, isLoading, getNextPage }
}
export default {
  components: {
    GoodItem
  },
  setup () {
    // 接收过滤条件数据
    const filterParams = inject('filterParams')
    // 处理列表渲染的钩子
    const { goodList, requestParams, isFinished, isLoading, getNextPage } = useList(filterParams)
    watch(() => filterParams.value, () => {
      console.log('过滤条件：', filterParams.value)
      // getGoodsList()
      // 重置列表删除列表数据
      goodList.value = []
      requestParams.page = 0
      isLoading.value = false
      isFinished.value = false
    }, { deep: true })
    // 重点：监听filterParams的变化 =》 如果变化刷新列表
    // const getGoodsList = async () => {
    //   const { result: res } = await findSubCategoryGoods({ ...requestParams, ...filterParams.value })
    //   console.log('商品', res)
    //   goodList.value = res.items
    // }

    return { goodList, isLoading, isFinished, getNextPage }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
